package com.example.travel_front.Adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.travel_front.Model.Message;
import com.example.travel_front.R;

import java.util.List;

public class MessageAdapter extends RecyclerView.Adapter<MessageAdapter.ViewHolder> {

    private final List<Message> messageList;

    public MessageAdapter(List<Message> messageList) {
        this.messageList = messageList;

        // 用于访问资源
    }

    @NonNull
    @Override
    public MessageAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View messageView;
        // 根据消息类型决定使用哪个布局文件
        if (viewType == R.layout.layout_sent_message) {
            messageView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_sent_message, parent, false);
        } else {
            messageView = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_received_message, parent, false);
        }
        return new ViewHolder(messageView);
    }

    @Override
    public void onBindViewHolder(@NonNull MessageAdapter.ViewHolder holder, int position) {
        Message message = messageList.get(position);
        holder.messageTextView.setText(message.getContent());
        holder.itemView.requestLayout();
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    @Override
    public int getItemViewType(int position) {
        // 根据消息是发送还是接收来返回不同的布局文件
        return messageList.get(position).isSent() ? R.layout.layout_sent_message : R.layout.layout_received_message;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView messageTextView;

        public ViewHolder(View itemView) {
            super(itemView);
            messageTextView = itemView.findViewById(R.id.message_text);
        }
    }
}
